package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.Content;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.apache.commons.math3.ml.distance.CanberraDistance;
import org.ini4j.spi.Warnings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-12
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        Page<DeviceData> page=new Page(dto.getPageNum(),dto.getPageSize());
        //模糊查询设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
//            Wrappers.<DeviceData>lambdaQuery().eq(DeviceData::getDeviceName,dto.getDeviceName());
            lambdaQueryWrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        //精确查询功能名称
        if(StringUtils.isNotEmpty(dto.getFunctionId())){
//            Wrappers.<DeviceData>lambdaQuery().eq(DeviceData::getFunctionId,dto.getFunctionId());
            lambdaQueryWrapper.eq(DeviceData::getFunctionId,dto.getFunctionId());
        }
        //时间范围
        if(ObjectUtils.isNotEmpty(dto.getStartTime())&&ObjectUtils.isNotEmpty(dto.getEndTime())){
//            Wrappers.<DeviceData>lambdaQuery().between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
            lambdaQueryWrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }
        //分页查询
        page=page(page,lambdaQueryWrapper);
        //封装对象
        return getTableDataInfo(page);
    }

    private TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量新增设备数据
     * @param content
     */
    @Override
    public void batchSaveDeviceData(Content content) {
        //根据iot_id设备表中数据查询这条设备相关的信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, content.getIotId()));
        //判断device是否存在，如果不存在直接返回
        if(ObjectUtils.isEmpty(device)){
            return;
        }
        //数据对应的设备存在，准备一个集合，用来存储一条数据中的多条物模型数据
        List<DeviceData> deviceDataList=new ArrayList<>();
        //遍历items 将数据封装到DeviceData中，并添加到deviceDataList中
        content.getItems().forEach((key,item)->{
            DeviceData deviceData=DeviceData.builder()
                    .deviceName(content.getDeviceName())
                    .iotId(content.getIotId())
                    .nickname(device.getNickname())
                    .productKey(device.getProductKey())
                    .productName(device.getProductName())
                    .functionId(key)
                    .accessLocation(device.getRemark())
                    .locationType(device.getLocationType())
                    .physicalLocationType(device.getPhysicalLocationType())
                    .deviceDescription(device.getDeviceDescription())
                    .dataValue(item.getValue()+"")
                    .alarmTime(LocalDateTimeUtil.of(item.getTime()))
                    .build();
            //将数据添加到集合中
            deviceDataList.add(deviceData);
        });
        //判断是否是睡眠时间，需要单独设置
//        if("lichuangshijian".equals(key)){
//            DateTime date= DateUtil.date(item.getValue);
//            deviceData.setDataValue(DateUtil.formatDateTime(date));
//        }else{
//            deviceData.setDataValue(item.getValue+"");
//        }
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LATEST_DATA,device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
        //批量保存数据到设备数据表中
        saveBatch(deviceDataList);

    }
}
